JavaScript modules allow you to break up your code into separate files, making it easier to maintain and
organize. Modules are imported from external files with the import
statement and exported using the
export
statement.
There are two types of exports: named exports and default exports.
Named exports allow you to export multiple values. You can create named exports in two ways:
// In-line individually
export const name = "John";
export const age = 30;
// All at once at the bottom
const name = "John";
const age = 30;
export { name, age };
Default exports allow you to export a single value or to have a fallback value for your module:
const message = () => {
return "Hello, World!";
};
export default message;
You can import modules into a file in two ways, based on whether they are named exports or default exports.
import { name, age } from './person.js';
import message from './message.js';
Here is an example demonstrating how to use modules:
// person.js
export const name = "John";
export const age = 30;
// message.js
const message = () => {
return `Hello, my name is ${name} and I am ${age} years old.`;
};
export default message;
// main.js
import { name, age } from './person.js';
import message from './message.js';
console.log(name); // John
console.log(age); // 30
console.log(message()); // Hello, my name is John and I am 30 years old.
For more detailed information, you can check out resources like W3Schools[^1^][1] and MDN Web Docs[^2^][2].